<!-- eslint-disable no-console -->
<script lang="ts" setup>
import { onBeforeUnmount, onMounted, ref } from 'vue'
import * as monaco from 'monaco-editor'

import EditorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker'
import JsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker'

const props = defineProps({
  modelValue: String,
  readOnly: {
    type: Boolean,
    default: false,
  },
  language: {
    type: String,
    default: 'json',
  },
})

const emit = defineEmits(['update:modelValue']);

// eslint-disable-next-line no-restricted-globals
(self as any).MonacoEnvironment = {
  getWorker(workerId: any, label: any) {
    if (label === 'json') {
      return new JsonWorker()
    }
    return new EditorWorker()
  },
}

const dom = ref()

let editor: any = null

let parentContainer: any = null
const wheelOptions = { capture: true, passive: false }
function customWheel(event: any) {
  if (!editor.getDomNode().contains(event.target))
    return

  const deltaY = event.deltaY
  const scrollTop = editor.getScrollTop()
  const editorHeight = editor.getLayoutInfo().height
  const scrollHeight = editor.getScrollHeight()

  // 判断是否滚动到底部
  const isAtBottom = scrollTop + editorHeight >= scrollHeight

  // 判断是否滚动到顶部
  const isAtTop = scrollTop <= 0

  if ((isAtTop && deltaY < 0) || (isAtBottom && deltaY > 0)) {
    event.stopPropagation() // 允许父容器滚动
  }
}

onMounted(() => {
  editor = monaco.editor.create(dom.value, {
    tabSize: 2,
    automaticLayout: true,
    scrollBeyondLastLine: false,
    value: '// 测试滚动\n'.repeat(50),
    language: props.language, // 此处使用的python，其他语言支持自行查阅demo
    theme: 'vs', // 官方自带三种主题vs, hc-black, or vs-dark
    selectOnLineNumbers: true, // 显示行号
    roundedSelection: false,
    readOnly: props.readOnly, // 只读
    cursorStyle: 'line', // 光标样式
    glyphMargin: true, // 字形边缘
    useTabStops: false,
    fontSize: 14, // 字体大小
    autoIndent: 'advanced', // 自动布局
    quickSuggestionsDelay: 100, // 代码提示延时
    lineNumbersMinChars: 1,
    minimap: {
      enabled: false, // 关闭小地图,
    },
  })

  editor.onDidChangeModelContent(() => {
    const value = editor.getValue()
    emit('update:modelValue', value)
  })

  // 滚动事件处理
  parentContainer = document.querySelector('.parent-container')
  parentContainer.addEventListener('wheel', customWheel, wheelOptions)
})

onBeforeUnmount(() => {
  if (editor) {
    editor.dispose() // 清理编辑器实例和监听器
    editor = null
  }
  parentContainer.removeEventListener('wheel', customWheel, wheelOptions)
})
</script>

<template>
  <div class="parent-container" style="height: 300px; width: 100%;overflow: auto;">
    <div style="height: 100px;margin-bottom: 8px;background: white">
      上方内容
    </div>
    <div ref="dom" class="editor" style="height: 600px;overflow: auto; /* 允许滚动 */" />
    <div style="height: 100px;margin-top: 8px;background: white">
      下方内容
    </div>
  </div>
</template>

<style scoped>
</style>
